/**
 * Sleeper.java
 */
package com.mht2017.common.utils;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 睡眠器，为各个模块提供睡眠服务的工具
 *
 * @author yutong.xiao
 */
public class Sleeper {

	private static final Logger LOGGER = LoggerFactory.getLogger(Sleeper.class);

	private ReentrantLock lock = new ReentrantLock();
	private Condition sleepCondition = lock.newCondition();

	private long sleepInMillis;
	private String actionName;

	public Sleeper(String actionName, long sleepInMillis) {
		this.actionName = String.format("%s_%s", actionName, Sleeper.class.getSimpleName());
		this.sleepInMillis = sleepInMillis;
		LOGGER.info(String.format("%s-睡眠器-睡眠时间: '%s'ms", actionName, sleepInMillis));
	}

	public void await() {
		try {
			lock.lockInterruptibly();
			sleepCondition.await();
		} catch (InterruptedException e) {
			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug(String.format("%s-等待被打断: '%s'", actionName, e.getMessage()));
			}
		} finally {
			lock.unlock();
		}
	}

	public void sleep() {
		try {
			lock.lockInterruptibly();
			sleepCondition.await(sleepInMillis, TimeUnit.MILLISECONDS);
		} catch (InterruptedException e) {
			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug(String.format("%s-睡眠被打断: '%s'", actionName, e.getMessage()));
			}
		} finally {
			lock.unlock();
		}
	}

	public void wakeup() {
		try {
			lock.lock();
			sleepCondition.signal();
		} finally {
			lock.unlock();
		}
	}
}
